<script setup lang="ts">
import { nextTick, onMounted, ref } from "vue";
import RelationGraph from "relation-graph/vue3";
import { ArrayUtils } from "../src/utils";
import type { PlayerPlanet } from "../src/repositories/plants/entity/PlayerPlanet";
import UniverseTypeIcon from "~components/universe-type/UniverseTypeIcon.vue";

const props = defineProps<{ planet: PlayerPlanet }>();

const options = {
  debug: false,
  defaultNodeBorderWidth: 0,
  defaultNodeColor: "rgba(238, 178, 94, 1)",
  allowSwitchLineShape: true,
  allowSwitchJunctionPoint: true,
  defaultLineShape: 1,
  layouts: [
    {
      label: "Auto Layout",
      layoutName: "force",
      layoutClassName: "seeks-layout-force",
    },
  ],
  defaultJunctionPoint: "border",
};

const graphRef = ref<RelationGraph>();

const getJsonData = (planet: PlayerPlanet): any => {
  console.log(planet);
  const nodes = planet.layout.pins
    //@ts-ignore
    .filter((p) => p.type.groupId !== 1027)
    //@ts-ignore
    .map((pin) => ({
      id: `${pin.pin_id}`,

      data: {
        items: pin.contents ?? [],
      },
      text: `${pin.type.name}`,
    }));
  const groupRoutes = ArrayUtils.group(planet.layout.routes, (e) => e.source_pin_id);
  const routes = nodes.flatMap((node) => {
    const routes = groupRoutes.get(Number(node.id))!;
    if (!routes) return [];
    return routes
      .filter((e) => e.source_pin_id === Number(node.id))
      .map((pin) => ({
        from: `${pin.source_pin_id}`,
        to: `${pin.destination_pin_id}`,
        color: routes.length === 1 ? "#79bbff" : "#95d475",
        //@ts-ignore
        text: `${pin.type.name}(${pin.quantity})`,
      }));
  });
  return {
    nodes,
    links: routes,
  };
};
onMounted(() => {
  nextTick(() => {
    graphRef.value!.setJsonData(getJsonData(props.planet));
  });
});
</script>

<template>
  <RelationGraph ref="graphRef" :options="options">
    <template #node="{ node }">
      <el-tooltip content="1" :disabled="node.data.items.length === 0">
        <div class="flex items-center h-full">
          {{ node.text }}
        </div>
        <template #content>
          <div class="flex flex-col space-y-2">
            <div v-for="content in node.data.items" :key="content.type_id" class="flex space-x-2">
              <UniverseTypeIcon :id="content.type_id" /> {{ content.type.name }} {{ content.amount }}
            </div>
          </div>
        </template>
      </el-tooltip>
    </template>
  </RelationGraph>
</template>

<style scoped lang="scss"></style>
